package pers.acp.test.application.controller

import io.gitee.zhangbinhub.acp.boot.exceptions.WebException
import io.gitee.zhangbinhub.acp.boot.http.HttpStatus
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.acp.boot.tools.IpTools
import io.gitee.zhangbinhub.acp.boot.tools.ServerTools
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.noear.solon.annotation.*
import org.noear.solon.core.util.MimeType
import org.noear.solon.core.handle.Context
import org.noear.solon.validation.annotation.Valid
import org.noear.solon.validation.annotation.Validated
import pers.acp.test.application.po.TestPo
import java.net.InetAddress

@Api("控制器")
@Valid
@Controller
open class TestController(
    private val logAdapter: LogAdapter,
    private val serverTools: ServerTools
) {
    @ApiOperation("post-hello1")
    @Post
    @Mapping("/hello")
    fun hello(): String {
        return "home，" + CommonTools.getWebRootAbsPath() + "，" + InetAddress.getLocalHost().hostAddress
    }

    @ApiOperation("post-json1")
    @Post
    @Consumes(MimeType.APPLICATION_JSON_VALUE)
    @Produces(MimeType.APPLICATION_JSON_VALUE)
    @Mapping("/json")
    fun json1(@Body @Validated testPo: TestPo): TestPo = testPo.apply {
        logAdapter.info("request: $testPo")
        this.value = "rsp:" + this.value
    }

    @ApiOperation("post-error")
    @Post
    @Consumes(MimeType.APPLICATION_JSON_VALUE)
    @Produces(MimeType.APPLICATION_JSON_VALUE)
    @Mapping("/error")
    fun error(@Body testPo: TestPo, context: Context): TestPo {
        logAdapter.info("remote ip: ${IpTools.getRemoteIP(context)}")
        logAdapter.info("local ip: ${serverTools.getServerIp()}")
        logAdapter.info("local mac: ${IpTools.getMacAddress()}")
        throw WebException(HttpStatus.BAD_GATEWAY, "123error")
    }

    @ApiOperation("post-xml1")
    @Post
    @Consumes(MimeType.APPLICATION_XML_VALUE)
    @Produces(MimeType.APPLICATION_XML_VALUE)
    @Mapping("/xml1")
    fun xml1(@Body testPo: TestPo): TestPo = testPo.apply {
        logAdapter.info("request: $testPo")
        this.value = "rsp:" + this.value
    }
}